package cn.syw.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import cn.syw.dao.iface.RoleDao;
import cn.syw.db.utils.JdbcTemplate;
public class RoleJdbcDaoImpl implements RoleDao {
	@Override
	public List<Map<String, Object>> queryRoles() {
		String sql = "select ur.id,u.name,r.rolename " + 
				"from users u   " + 
				"right outer join userrole ur on u.id = ur.userid " + 
				"left outer join role r on ur.roleid = r.id";
		List<Map<String,Object>> list = JdbcTemplate.query(sql, (rs)->{
			List<Map<String,Object>> list1 = new ArrayList<>();
			try {
				while(rs.next()) {
					Map<String,Object> map = new HashMap<>();
					for(int len = rs.getMetaData().getColumnCount(),i=1;i<=len;i++) {
						map.put(rs.getMetaData().getColumnName(i), rs.getObject(i));
					}
					list1.add(map);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return list1;
		},new Object[] {});
		return list;
	}

	@Override
	public Map<String, Object> queryById(String id) {
		String sql = "select ur.id,u.name,r.rolename " + 
				"from users u  " + 
				"right outer join userrole ur on u.id = ur.userid  " + 
				"left outer join role r on ur.roleid = r.id " + 
				"where ur.id = ?";
		Map<String, Object> map = JdbcTemplate.query(sql, (rs)->{
			Map<String,Object> role = new HashMap<>();
			try {
				while(rs.next()) {
					for(int i = 1,len = rs.getMetaData().getColumnCount();i<=len;i++) {
						role.put(rs.getMetaData().getColumnName(i), rs.getObject(i));
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return role;
		}, id);
		return map;
	}

	@Override
	public int deleteRole(String id) {
		String sql = "delete from userrole where id = ?";
		int num = JdbcTemplate.update(sql, id);
		return num;
	}

	@Override
	public int deleteUserRole(String id) {
		String sql = "delete from userrole where userid = ?";
		int num = JdbcTemplate.update(sql, id);
		return num;
	}

}
